package com.bbzn.device.client.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bbzn.device.client.vo.req.ContactVO;
import com.bbzn.device.client.vo.req.SosVO;
import com.bbzn.device.client.aspect.OperationAnnotation;
import com.bbzn.device.client.config.EmqCode;
import com.bbzn.device.client.constant.ContactConstant;
import com.bbzn.device.client.constant.CrudConstant;
import com.bbzn.device.client.constant.RedisConstant;
import com.bbzn.device.client.constant.SosConstant;
import com.bbzn.device.client.dataobject.Contact;
import com.bbzn.device.client.dataobject.Sos;
import com.bbzn.device.client.dataobject.SystemParam;
import com.bbzn.device.client.exception.DefinitException;
import com.bbzn.device.client.service.*;
import com.bbzn.device.client.utils.BaseApiService;
import com.bbzn.device.client.utils.BaseResponse;
import com.bbzn.device.client.utils.MayiktJwtUtils;
import com.bbzn.device.client.utils.OptionalBean;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @Author 黄志鹏
 * @Date 2021/3/16 17:11
 * @Version 1.0
 */

@RestController
@RequestMapping("/contact")
@Slf4j
//@CrossOrigin
public class ContactController extends BaseApiService {


    @Autowired
    private SystemParamByCacheService systemParamByCacheService;

    @Autowired
    private ContactService contactService;

    @Autowired
    private CommonService commentService;

    @Autowired
    private SosService sosService;

    @Autowired
    private PublishService publishService;


    /**
     * 查询白名单
     *
     * @param reqVO
     * @param request
     * @return
     * @throws Exception
     */
    @OperationAnnotation(content = "查询白名单")
    @RequestMapping(value = "/getContact", method = RequestMethod.POST)
    public BaseResponse getContact(@RequestBody ContactVO reqVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
//        String secretKey = commentService.getWebSalt(request);
        String secretKey = commentService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commentService.getUserId(request);
        if (!OptionalBean.ofNullable(reqVO.getImei()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ContactConstant.CONTACT_ENUM, ContactConstant.CONTACT_NO_IMEI_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        Contact contact = new Contact();
        contact.setImei(reqVO.getImei());
        List<Contact> contacts = contactService.findByAll(contact);
        JSONArray jsonArray = null;
        if (CollectionUtils.isNotEmpty(contacts) && OptionalBean.ofNullable(contacts.get(0).getContactList()).isPresent()) {
            jsonArray = JSONArray.parseArray(contacts.get(0).getContactList());
            contact.setCreateTime(contacts.get(0).getCreateTime());
            contact.setCreatedBy(contacts.get(0).getCreatedBy());
            contact.setUpdateTime(contacts.get(0).getUpdateTime());
            contact.setUpdatedBy(contacts.get(0).getUpdatedBy());
            contact.setIsOpen(contacts.get(0).getIsOpen());
        } else {
            jsonArray = new JSONArray();
            contact.setIsOpen(0);
        }

        int count = 5 - jsonArray.size();
        for (int i = 0; i < count; i++) {
            JSONObject json = new JSONObject();
            json.put("name", "");
            json.put("phone", "");
            json.put("relation", "");
            jsonArray.add(json);
        }
        contact.setContactList(jsonArray.toJSONString());
        return setResultSuccess(contact);
    }


    /**
     * 编辑白名单
     * 不能通过id,可能不存在，只能通过卡号做存在即更新
     * <p>
     * 走最终一致性
     * 1.入库
     * 2.下发指令
     *
     * @param reqVO
     * @param request
     * @return
     * @throws Exception
     */

    @RequestMapping(value = "/updateContact", method = RequestMethod.POST)
    @OperationAnnotation(content = "编辑白名单")
    public BaseResponse updateContact(@RequestBody ContactVO reqVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commentService.getAppSalt(request);
//        String secretKey = commentService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commentService.getUserId(request);
        String username = MayiktJwtUtils.getUsername(request,secretKey);
        if (!OptionalBean.ofNullable(reqVO.getImei()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ContactConstant.CONTACT_ENUM, ContactConstant.CONTACT_NO_IMEI_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getContactInfoList()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ContactConstant.CONTACT_ENUM, ContactConstant.CONTACT_NO_CONTACTLIST_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getIsOpen()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(ContactConstant.CONTACT_ENUM, ContactConstant.CONTACT_NO_IS_OPEN_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (StringUtils.isEmpty(username)) {
            systemParam = systemParamByCacheService.getValues(RedisConstant.REDIS_ENUM, RedisConstant.TOKEN_CACHE_EXCEPTION_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        Contact contact = new Contact();
        contact.setImei(reqVO.getImei());
        contact.setContactList(JSON.toJSONString(reqVO.getContactInfoList()));
        contact.setIsOpen(reqVO.getIsOpen());
        contact.setCreateTime(new Date());
        contact.setCreatedBy(username);
        contactService.insertOrUpdateSelective(contact);

        // 2.发送消息 【黑白名单列表（设置通讯录）】

        // 组装json
        JSONObject data = new JSONObject();
        data.put("code", EmqCode.contactListCode);
        data.put("imei", contact.getImei());
        data.put("contactList", contact.getContactList());
        data.put("isOpen", contact.getIsOpen());
        // 推送黑白名单列表（设置通讯录）topic给设备
        publishService.sendToMqtt(data.toJSONString(), EmqCode.sendTopic + contact.getImei() + EmqCode.endTopic);
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.MODIFY_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }


    /**
     * 获取SOS信息
     *
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "获取SOS信息", produces = "application/json")
    @RequestMapping(value = "/getSosInfo", method = RequestMethod.POST)
    @ApiOperationSupport(ignoreParameters = {"reqVO.id", "reqVO.isOpen", "reqVO.phone", "reqVO.name"})
    public BaseResponse getSosInfo(@RequestBody SosVO reqVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commentService.getAppSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commentService.getUserId(request);
        if (!OptionalBean.ofNullable(reqVO.getImei()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(SosConstant.SOS_ENUM, SosConstant.SOS_NO_IMEI_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        Sos sos = new Sos();
        sos.setImei(reqVO.getImei());
        List<Sos> list = sosService.findByAll(sos);
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.SELECT_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage(), list);
    }
}
